package com.hzf.wxplatform.web.controller.manager.designer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.util.Base64;
import com.github.wenhao.geohash.GeoHash;
import com.github.wenhao.geohash.GeoSearch;
import com.github.wenhao.geohash.domain.GeoRange;
import com.hzf.api.rpc.api.ApiService;
import com.hzf.common.base.BaseController;
import com.hzf.common.util.ByteUtils;
import com.hzf.common.util.EhCacheUtil;
import com.hzf.common.util.JsonListUtil;
import com.hzf.common.util.RedisUtil;
import com.hzf.config.dao.model.*;
import com.hzf.designer.dao.model.*;
import com.hzf.material.dao.model.MaterialGoods;
import com.hzf.material.dao.model.MaterialGoodsModel;
import com.hzf.material.dao.model.MaterialGoodsModelExample;
import com.hzf.ucenter.dao.model.*;
import com.hzf.wxplatform.common.WxplatformResult;
import com.hzf.wxplatform.common.WxplatformResultConstant;
import com.hzf.wxplatform.common.utils.UcenterUserUtils;
import com.hzf.wxplatform.common.utils.WxGetGpsUtils;
import com.hzf.wxplatform.web.utils.BatyWebUtils;
import com.hzf.wxplatform.web.utils.GeoHashHelper;
import com.sun.xml.internal.rngom.parse.host.Base;
import io.swagger.annotations.Api;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.DecimalFormat;
import java.util.*;

@Controller
@RequestMapping("/designerIndex")
public class DesignerIndexController extends BaseController {
    @Autowired
    ApiService apiService;
    @RequestMapping(value="/lockSheji")
    public String  lockSheji(Model model,HttpServletRequest request ){
        HttpSession session = request.getSession();
        UcenterUser ucenterUser = new UcenterUser();
        ConfigRegion configRegion = new ConfigRegion();
        byte[] user = UcenterUserUtils.getUser(session);
        if (null == user) {
            model.addAttribute("data", "您的操作属于非法操作，所查看商品或设计师非您账户，请核实。");
            return thymeleaf("/404");
        }
        ucenterUser = (UcenterUser) ByteUtils.ByteToObject(user);

        if (null == ucenterUser) {
            model.addAttribute("data", "您的操作属于非法操作，所查看商品或设计师非您账户，请核实。");
            return thymeleaf("/404");
        }
        return  thymeleaf("/SJS/SJS_LookSheJiShi");

    }
    @RequestMapping(value = "/lockDesigner",method = RequestMethod.POST)
    @ResponseBody
    public Object lockDesigner(int distanceType,HttpServletRequest request,Model model){



        /*   GeoHash geoHash = GeoHash.fromCoordinate(lat,lng);*/
        HttpSession session = request.getSession();
        UcenterUser ucenterUser = new UcenterUser();
        ConfigRegion configRegion = new ConfigRegion();
        byte[] user = UcenterUserUtils.getUser(session);
        ucenterUser = (UcenterUser) ByteUtils.ByteToObject(user);

        String dqaddress = RedisUtil.get("dangqianweizhi"+ucenterUser.getId());
        net.sf.json.JSONObject jsonobject = net.sf.json.JSONObject.fromObject(dqaddress);
        UcenterUserCity usercity= (UcenterUserCity) net.sf.json.JSONObject.toBean(jsonobject,UcenterUserCity.class);
        double lat=usercity.getLat();
        double lng=usercity.getLng();
        DecimalFormat df = new DecimalFormat("######0.00");

        if (null == ucenterUser) {
            model.addAttribute("data", "您的操作属于非法操作，所查看商品或设计师非您账户，请核实。");
            return thymeleaf("/404");
        }
        byte[] address = UcenterUserUtils.getAddress(ucenterUser.getId());
        configRegion = (ConfigRegion) ByteUtils.ByteToObject(address);

        int distanceCount = 0;
// N, NE, E, SE, S, SW, W, NW
        if (distanceType == 0) {
            distanceCount = 2000;
        } else if (distanceType == 1) {
            distanceCount = 5000;

        } else if (distanceType == 2) {
            distanceCount = 10000;

        } else if (distanceType == 3) {
            distanceCount = 20000;

        } else if (distanceType == 4) {
            distanceCount = 50000;

        }
        String json = RedisUtil.get(ucenterUser.getId() + "DneedDesignerLNG");
        List<DneedsDesigner> listarray = JSONArray.parseArray(json, DneedsDesigner.class);
        if(null!=listarray&&0!=listarray.size()){}else{
            listarray=new ArrayList<>();
        }
        List<DneedsDesigner> list=new ArrayList<>();
        list = selcetDneedDesigner(distanceCount, lat, lng, ucenterUser, configRegion);

        for (DneedsDesigner dneedsDesigner : list) {

            com.github.wenhao.geohash.GeoHash geoHash = com.github.wenhao.geohash.GeoHash.fromLong(dneedsDesigner.getGeoCode());
            double distance = geoHash.distance(lat, lng);
            double distanceKm = distance / 1000;
            dneedsDesigner.setDistanceKm(Double.valueOf(df.format(distanceKm)));
            UcenterUserExample ucenterUserExample  = new UcenterUserExample();
            ucenterUserExample.createCriteria().andIdEqualTo(dneedsDesigner.getUserId());
            ucenterUser = apiService.getUser(ucenterUserExample);
            dneedsDesigner.setUserName(ucenterUser.getUserName());
            DneedsDesignerCaseExample dneedsDesignerCaseExample = new DneedsDesignerCaseExample();
            dneedsDesignerCaseExample.createCriteria().andUserIdEqualTo(ucenterUser.getId());
            List<DneedsDesignerCase> caseList  =apiService.selectDneedsDesignerCase(dneedsDesignerCaseExample);
            dneedsDesigner.setAnliCount(caseList.size());
            dneedsDesigner.setPhone(ucenterUser.getPhone());
           }


        String json1 = JSONArray.toJSONString(list);
        RedisUtil.del_add(ucenterUser.getId() + "DneedDesignerLNG", json1);
        Map map = new HashMap();
        map.put("lng", lng);
        map.put("lat", lat);
        map.put("distanceType", distanceType);
        map.put("list", list);
        return new WxplatformResult(WxplatformResultConstant.SUCCESS, map);

    }
    private List<DneedsDesigner> selcetDneedDesigner(int dict, double lat, double lng, UcenterUser ucenterUser,  ConfigRegion configRegion) {
        Map<String,Long>map= GeoHashHelper.getMax(lat,lng,dict);
        List<DneedsDesigner> list = apiService.selectByPrimaryDneedsDesigner(configRegion.getRegionNumber().intValue(),0,map.get("min0"), map.get("max0"),
                map.get("min1"), map.get("max1"),
                map.get("min2"), map.get("max2"),
                map.get("min3"), map.get("max3"),
                map.get("min4"), map.get("max4"),
                map.get("min5"), map.get("max5"),
                map.get("min6"), map.get("max6"),
                map.get("min7"), map.get("max7"),
                map.get("min8"), map.get("max8"));
        int a = 1000;

        if(null==list||list.size()<4){
            for(int i =1000;i<50000;i++){
                if(dict==50000){
                    map= GeoHashHelper.getMax(lat,lng,dict);
                    list =  apiService.selectByPrimaryDneedsDesigner(configRegion.getRegionNumber().intValue(),0,map.get("min0"), map.get("max0"),
                            map.get("min1"), map.get("max1"),
                            map.get("min2"), map.get("max2"),
                            map.get("min3"), map.get("max3"),
                            map.get("min4"), map.get("max4"),
                            map.get("min5"), map.get("max5"),
                            map.get("min6"), map.get("max6"),
                            map.get("min7"), map.get("max7"),
                            map.get("min8"), map.get("max8"));
                    List<DneedsDesigner> removeList = new ArrayList<>();

                    if(null!=list) {
                        for (DneedsDesigner dneedsDesigner : list) {

                            com.github.wenhao.geohash.GeoHash geoHash = com.github.wenhao.geohash.GeoHash.fromLong(dneedsDesigner.getGeoCode());
                            double distance = geoHash.distance(lat, lng);
                            if (distance > dict) {
                                removeList.add(dneedsDesigner);
                            } else {
                            }
                        }
                       list.removeAll(removeList);
                    }

                    if(null!=list&&list.size()>=4){
                        break;
                    }else{
                        break;

                    }
                }else{
                    map= GeoHashHelper.getMax(lat,lng,dict);
                    list =  apiService.selectByPrimaryDneedsDesigner(configRegion.getRegionNumber().intValue(),0,map.get("min0"), map.get("max0"),
                            map.get("min1"), map.get("max1"),
                            map.get("min2"), map.get("max2"),
                            map.get("min3"), map.get("max3"),
                            map.get("min4"), map.get("max4"),
                            map.get("min5"), map.get("max5"),
                            map.get("min6"), map.get("max6"),
                            map.get("min7"), map.get("max7"),
                            map.get("min8"), map.get("max8"));
                    List<DneedsDesigner> removeList = new ArrayList<>();

                    if(null!=list) {
                        for (DneedsDesigner dneedsDesigner : list) {

                            com.github.wenhao.geohash.GeoHash geoHash = com.github.wenhao.geohash.GeoHash.fromLong(dneedsDesigner.getGeoCode());
                            double distance = geoHash.distance(lat, lng);
                            if (distance > dict) {
                                removeList.add(dneedsDesigner);
                            } else {
                            }
                        }
                        list.removeAll(removeList);
                    }
                    if(null!=list&&list.size()>=4){
                        break;
                    }else{
                        if(dict==2000){
                            dict=5000;
                        }else if(dict==5000){
                            dict=10000;
                        }else if(dict==10000){
                            dict=20000;
                        }else if(dict==20000){
                            dict=50000;
                        }
                    }
                }

            }
            return list;

        }else{
            return list;

        }




    }
    @RequestMapping(value="/designerInfo")
    public  String designerInfo(Model model,int id,HttpServletRequest request){
        HttpSession session = request.getSession();
        UcenterUser ucenterUser = new UcenterUser();
        ConfigRegion configRegion = new ConfigRegion();
        byte[] user = UcenterUserUtils.getUser(session);
        if (null == user) {
            model.addAttribute("data", "您的操作属于非法操作，所查看商品或设计师非您账户，请核实。");
            return thymeleaf("/404");
        }
        ucenterUser = (UcenterUser) ByteUtils.ByteToObject(user);
        DecimalFormat df = new DecimalFormat("######0.00");

        if (null == ucenterUser) {
            model.addAttribute("data", "您的操作属于非法操作，所查看商品或设计师非您账户，请核实。");
            return thymeleaf("/404");
        }
        DneedsDesignerExample dneedsDesignerExample = new DneedsDesignerExample();
        dneedsDesignerExample.createCriteria().andIdEqualTo(id);
        DneedsDesigner dneedsDesigner = apiService.getDesigner(dneedsDesignerExample);
        DneedsDesignerCaseExample dneedsDesignerCaseExample = new DneedsDesignerCaseExample();
        dneedsDesignerCaseExample.createCriteria().andUserIdEqualTo(dneedsDesigner.getUserId());
        List<DneedsDesignerCase>dneedsDesignerCases = apiService.selectDneedsDesignerCase(dneedsDesignerCaseExample);
        UcenterAuthInfoExample ucenterAuthInfoExample = new UcenterAuthInfoExample();
        ucenterAuthInfoExample.createCriteria().andUserIdEqualTo(dneedsDesigner.getUserId());
        UcenterAuthInfo ucenterAuthInfo = apiService.selectUserinfo(ucenterAuthInfoExample);
        dneedsDesigner.setUserName(ucenterAuthInfo.getName());
        dneedsDesigner.setPhone(ucenterAuthInfo.getPhone());
        if(null!=dneedsDesignerCases){
            dneedsDesigner.setAnliCount(dneedsDesignerCases.size());
        }else{
            dneedsDesigner.setAnliCount(0);
        }
        model.addAttribute("dneedsDesignerCases",dneedsDesignerCases);
        model.addAttribute("data",dneedsDesigner);

        return  thymeleaf("/SJS/SJS_XiangQingYe");

    }

    /**
     * 队列比较
     *
     * @param <T>
     * @param a
     * @param b
     * @return
     */
    public static <T extends Comparable<T>> boolean compare(List<T> a, List<T> b) {
        if (a.size() != b.size())
            return false;
        Collections.sort(a);
        Collections.sort(b);
        for (int i = 0; i < a.size(); i++) {
            if (!a.get(i).equals(b.get(i)))
                return false;
        }
        return true;
    }
}
